package com.immunology.bean;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.immunology.database.ConnectionManager;
import com.immunology.database.DbColumns;
import com.immunology.model.User;
import com.immunology.model.enums.Role;

public class UserBean {

	public List<User> getUserListFromDatabase() {
		List<User> userList = new ArrayList<User>();

		ConnectionManager connectionManager = new ConnectionManager();
		Connection connection = connectionManager.getConnection();

		Statement statement = null;
		ResultSet resultSet = null;
		try {
			statement = connection.createStatement();
			try {
				String sql = "SELECT * FROM user";
				resultSet = statement.executeQuery(sql);
			} catch (Exception e) {
				System.out.println("Getting objects error");
			}
		} catch (Exception e) {
			System.out.println("Creating statement error");
		}

		try {
			while (resultSet.next()) {
				User user = new User();
				user.setId(resultSet.getInt(DbColumns.FIRST_COLUMN));
				user.setFirstName(resultSet.getString(DbColumns.SECOND_COLUMN));
				user.setMiddleName(resultSet.getString(DbColumns.THIRD_COLUMN));
				user.setLastName(resultSet.getString(DbColumns.FOURTH_COLUMN));
				user.setLogin(resultSet.getString(DbColumns.FIFTH_COLUMN));
				user.setPassword(resultSet.getString(DbColumns.SIXTH_COLUMN));
				user.setRole(Role.fromValue(resultSet
						.getString(DbColumns.SEVENTH_COLUMN)));
				user.setPost(resultSet.getString(DbColumns.EIGHTH_COLUMN));
				userList.add(user);
			}
		} catch (SQLException e) {
			System.out.println("Can't read syndromes from database!");
			e.printStackTrace();
		} finally {
			try {
				statement.close();
				resultSet.close();
			} catch (SQLException e) {
				System.out.println("Can't close result set!");
				e.printStackTrace();
			}
		}

		if (connectionManager != null)
			connectionManager.closeConnection(connection);
		return userList;
	}

}
